package com.tornado.community.mapper.custome;

import com.tornado.community.dto.QuestionDto;
import com.tornado.community.model.Question;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Component;

import java.util.List;
@Component
@Mapper
public interface MyQuestionMapper {
    @Insert("INSERT INTO question (title, description, gmt_create, gmt_modify, creator, tag) VALUES (#{title}, #{description}, #{gmtCreate}, #{gmtModify}, #{creator}, #{tag})")
    void insert(Question question);

    @Select("SELECT q.id, q.title, q.gmt_create, q.gmt_modify, q.comment_count, q.view_count, q.like_count, u.avatar_url FROM question q LEFT JOIN user u ON q.creator = u.id ORDER BY q.gmt_modify DESC LIMIT #{offset},#{size}")
    List<QuestionDto> selectQuestionList(@Param("offset") int offset, @Param("size") int size);

    @Select("SELECT count(*) FROM question")
    Integer count();

    @Select("SELECT id, title, gmt_modify FROM question WHERE creator = #{creator} LIMIT #{offset},#{size}")
    List<Question> selectQuestionListByCreator(@Param("creator") int creator, @Param("offset") int offset, @Param("size") int size);

    @Select("SELECT count(*) FROM question WHERE creator = #{creator}")
    Integer countByCreator(@Param("creator") int creator);

    @Select("SELECT q.*, u.name, u.bio, u.avatar_url FROM (SELECT * FROM question WHERE id = #{id}) q LEFT JOIN user u ON q.creator = u.id")
    QuestionDto selectQuestionById(@Param("id") int id);

    @Update("UPDATE question SET title = #{title}, description = #{description}, tag = #{tag}, gmt_modify = #{gmtModify} WHERE id = #{id}")
    void update(QuestionDto question);

    @Update("UPDATE question SET view_count = view_count + 1 WHERE id = #{id}")
    void incView(@Param("id") int id);

    @Update("UPDATE question SET comment_count = comment_count + 1 WHERE id = #{id}")
    void incComment(@Param("id") int id);

    @Select("SELECT id, title FROM question WHERE id != #{id} AND tag REGEXP #{condition} LIMIT 10")
    List<Question> selectQuestionListByTag(@Param("id") int id, @Param("condition") String condition);
}
